import {
  _decorator,
  Collider2D,
  Component,
  Contact2DType,
  director,
  Director,
  Input,
  input,
  instantiate,
  Label,
  Node,
  Prefab,
  tween
} from "cc"
const { ccclass, property } = _decorator

@ccclass("gameRoot1")
export class gameRoot1 extends Component {
  @property(Node) bunny: Node
  @property(Node) hensRoot: Node
  @property(Node) eggsRoot: Node
  @property(Prefab) eggPrefab: Prefab
  @property(Label) scoreLabel: Label
  bunnyPosIndex = 2
  hensPosArr = []
  score = 0
  init() {
    this.hensRoot.children.forEach((item, index) => {
      this.hensPosArr[index] = item.position.x
    })
  }
  start() {
    this.init()
    this.openInputEvent()
    this.startCreateEggs()
    this.openCoillderEvent()
  }

  openCoillderEvent() {
    const comp = this.bunny.getComponent(Collider2D)
    comp.on(
      Contact2DType.BEGIN_CONTACT,
      (self, other) => {
        director.once(Director.EVENT_AFTER_PHYSICS, () => {
          other.node.destroy()
        })
        this.score++
        this.scoreLabel.string = "总分" + this.score
        console.log("碰撞了", other)
      },
      this
    )
  }
  createEgg() {
    const randomIndex = Math.floor(Math.random() * 5)
    const egg = instantiate(this.eggPrefab)
    this.eggsRoot.addChild(egg)
    egg.setPosition(this.hensPosArr[randomIndex], 0)
  }
  startCreateEggs() {
    this.schedule(this.createEgg, 2)
  }
  openInputEvent() {
    input.on(Input.EventType.KEY_DOWN, this.onKeyDown, this)
  }
  onKeyDown(e) {
    switch (e.keyCode) {
      case 37:
        this.bunnyAnimition(-1)
        console.log("left")
        break
      case 39:
        this.bunnyAnimition(1)
        console.log("right")
        break
    }
  }
  bunnyAnimition(move) {
    this.bunnyPosIndex += move
    if (this.bunnyPosIndex < 0) {
      this.bunnyPosIndex = 4
    }
    if (this.bunnyPosIndex > 4) {
      this.bunnyPosIndex = 0
    }
    this.bunny.setPosition(this.hensPosArr[this.bunnyPosIndex], this.bunny.position.y)
  }

  update(deltaTime: number) {
    this.eggsRoot.children.forEach((item, index) => {
      const { x, y } = item.getPosition()
      item.setPosition(x, y - 500 * deltaTime)
      if (y < -1000) {
        this.score > 0 ? this.score-- : ""
        item.destroy()
      }
    })
    this.scoreLabel.string = "总分" + this.score
  }
}
